/* Copyright 2007-2008 dnAnalytics Project.
 *
 * Contributors to this file:
 * Patrick van der Velde
 *
 * Redistribution and use in source and binary forms, with or without modification,
 * are permitted provided that the following conditions are met:
 * 
 * * Redistributions of source code must retain the above copyright notice, this 
 *   list of conditions and the following disclaimer.
 * * Redistributions in binary form must reproduce the above copyright notice, 
 *   this list of conditions and the following disclaimer in the documentation
 *   and/or other materials provided with the distribution.
 * * Neither the name of the dnAnalytics Project nor the names of its contributors
 *   may be used to endorse or promote products derived from this software without
 *   specific prior written permission.
 * 
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 
 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
 * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
 * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

using System;
using System.Diagnostics;
using dnAnalytics.Math;

namespace dnAnalytics.LinearAlgebra.Solvers
{
    /// <summary>
    /// Defines an <see cref="IIterationStopCriterium"/> that monitors residuals as stop criterium.
    /// </summary>
    public sealed class ResidualStopCriterium : IIterationStopCriterium
    {
        /// <summary>
        /// The default value for the maximum value of the residual.
        /// </summary>
        private const double sm_DefaultMaximum = 1e-12;

        /// <summary>
        /// The default value for the minimum number of iterations.
        /// </summary>
        private const int sm_DefaultMinimumIterations = 0;

        /// <summary>
        /// Defines the default last iteration number. Set to -1 because iterations normally
        /// start at 0.
        /// </summary>
        private const int sm_DefaultLastIterationNumber = -1;

        /// <summary>
        /// The default status.
        /// </summary>
        private static readonly ICalculationStatus sm_DefaultStatus = new CalculationIndetermined();

        /// <summary>
        /// Returns the default values for the maximum value for the residual below which the 
        /// calculation is considered converged.
        /// </summary>
        public static double DefaultMaximumResidual
        {
            get
            {
                return sm_DefaultMaximum;
            }
        }

        /// <summary>
        /// Returns the default value for the minimum number of iterations for which the residual 
        /// has to be below the maximum before the calculation is considered converged.
        /// </summary>
        public static int DefaultMinimumIterationsBelowMaximum
        {
            get 
            {
                return sm_DefaultMinimumIterations;
            }
        }

        /// <summary>
        /// The maximum value for the residual below which the calculation is considered converged.
        /// </summary>
        private double m_Maximum;

        /// <summary>
        /// The minimum number of iterations for which the residual has to be below the maximum before
        /// the calculation is considered converged.
        /// </summary>
        private int m_MinimumIterationsBelowMaximum;

        /// <summary>
        /// The status of the calculation
        /// </summary>
        private ICalculationStatus m_Status = sm_DefaultStatus;

        /// <summary>
        /// The number of iterations since the residuals got below the maximum.
        /// </summary>
        private int m_IterationCount;

        /// <summary>
        /// The iteration number of the last iteration.
        /// </summary>
        private int m_LastIteration = sm_DefaultLastIterationNumber;

        /// <summary>
        /// Creates an instance of the <c>ResidualStopCriterium</c> class with the default maximum 
        /// residual and the default minimum number of iterations.
        /// </summary>
        public ResidualStopCriterium()
            : this(sm_DefaultMaximum, sm_DefaultMinimumIterations)
        { }

        /// <summary>
        /// Creates an instance of the <c>ResidualStopCriterium</c> class with the specified 
        /// maximum residual and the default minimum number of iterations.
        /// </summary>
        /// <param name="maximum">
        ///   The maximum value for the residual below which the calculation is considered converged.
        /// </param>
        public ResidualStopCriterium(double maximum)
            : this(maximum, sm_DefaultMinimumIterations)
        { }

        /// <summary>
        /// Creates an instance of the <c>ResidualStopCriterium</c> class with the default maximum residual
        /// and specified minimum number of iterations.
        /// </summary>
        /// <param name="minimumIterationsBelowMaximum">
        ///   The minimum number of iterations for which the residual has to be below the maximum before
        ///   the calculation is considered converged.
        /// </param>
        public ResidualStopCriterium(int minimumIterationsBelowMaximum)
            : this(sm_DefaultMaximum, minimumIterationsBelowMaximum)
        { }

        /// <summary>
        /// Creates an instance of the <c>ResidualStopCriterium</c> class with the specified 
        /// maximum residual and minimum number of iterations.
        /// </summary>
        /// <param name="maximum">
        ///   The maximum value for the residual below which the calculation is considered converged.
        /// </param>
        /// <param name="minimumIterationsBelowMaximum">
        ///   The minimum number of iterations for which the residual has to be below the maximum before
        ///   the calculation is considered converged.
        /// </param>
        public ResidualStopCriterium(double maximum, int minimumIterationsBelowMaximum)
        {
            if (maximum < 0)
            {
                throw new ArgumentOutOfRangeException("maximum");
            }

            if (minimumIterationsBelowMaximum < 0)
            {
                throw new ArgumentOutOfRangeException("minimumIterationsBelowMaximum");
            }

            m_Maximum = maximum;
            m_MinimumIterationsBelowMaximum = minimumIterationsBelowMaximum;
        }

        /// <summary>
        /// Gets or sets the maximum value for the residual below which the calculation is considered 
        /// converged.
        /// </summary>
        /// <exception cref="ArgumentOutOfRangeException">Thrown if the <c>Maximum</c> is set to a negative value.</exception>
        public double Maximum
        {
            [DebuggerStepThrough]
            get
            {
                return m_Maximum;
            }
            [DebuggerStepThrough]
            set
            {
                if (value < 0)
                {
                    throw new ArgumentOutOfRangeException("value");
                }

                m_Maximum = value;
            }
        }

        /// <summary>
        /// Returns the maximum residual to the default.
        /// </summary>
        public void ResetMaximumResidualToDefault()
        {
            m_Maximum = sm_DefaultMaximum;
        }

        /// <summary>
        /// Gets or sets the minimum number of iterations for which the residual has to be
        /// below the maximum before the calculation is considered converged.
        /// </summary>
        /// <exception cref="ArgumentOutOfRangeException">Thrown if the <c>BelowMaximumFor</c> is set to a value less than 1.</exception>
        public int MinimumIterationsBelowMaximum
        {
            [DebuggerStepThrough]
            get
            {
                return m_MinimumIterationsBelowMaximum;
            }
            [DebuggerStepThrough]
            set
            {
                if (value < 0)
                {
                    throw new ArgumentOutOfRangeException("value");
                }

                m_MinimumIterationsBelowMaximum = value;
            }
        }

        /// <summary>
        /// Returns the minimum number of iterations to the default.
        /// </summary>
        public void ResetMinimumIterationsBelowMaximumToDefault()
        {
            m_MinimumIterationsBelowMaximum = sm_DefaultMinimumIterations;
        }

        /// <summary>
        /// Determines the status of the iterative calculation based on the stop criteria stored
        /// by the current <c>IIterationStopCriterium</c>.
        /// </summary>
        /// <param name="iterationNumber">The number of iterations that have passed so far.</param>
        /// <param name="solutionVector">The vector containing the current solution values.</param>
        /// <param name="sourceVector">The right hand side vector.</param>
        /// <param name="residualVector">The vector containing the current residual vectors.</param>
        /// <returns>
        ///   An <c>ICalculationStatus</c> which indicates what the status of the iterative 
        ///   calculation is according to the current <c>IIterationStopCriterium</c>.
        /// </returns>
        /// <remarks>
        /// The individual stop criteria may internally track the progress of the calculation based
        /// on the invocation of this method. Therefore this method should only be called if the 
        /// calculation has moved forwards at least one step.
        /// </remarks>
        public void DetermineStatus(int iterationNumber, Vector solutionVector, Vector sourceVector, Vector residualVector)
        {
            if (iterationNumber < 0)
            {
                throw new ArgumentOutOfRangeException("iterationNumber");
            }

            if (solutionVector == null)
            {
                throw new ArgumentNullException("solutionVector");
            }

            if (sourceVector == null)
            {
                throw new ArgumentNullException("sourceVector");
            }
            
            if (residualVector == null)
            {
                throw new ArgumentNullException("residualVector");
            }

            if (solutionVector.Count != sourceVector.Count)
            {
                throw new NotConformableException();
            }

            if (solutionVector.Count != residualVector.Count)
            {
                throw new NotConformableException();
            }

            // Store the infinity norms of both the solution and residual vectors
            // These values will be used to calculate the relative drop in residuals
            // later on.
            double residualNorm = residualVector.InfinityNorm();
            
            // Check the residuals by calculating:
            // ||r_i|| <= stop_tol * ||b||
            double stopCriterium = ComputeStopCriterium(sourceVector.InfinityNorm());

            // First check that we have real numbers not NaN's.
            // NaN's can occur when the iterative process diverges so we
            // stop if that is the case.
            if ((Double.IsNaN(stopCriterium)) || (double.IsNaN(residualNorm)))
            {
                m_IterationCount = 0;
                SetStatusToDiverged();
                return;
            }

            // ||r_i|| <= stop_tol * ||b||
            // Stop the calculation if it's clearly smaller than the tolerance
            int decimalMagnitude = System.Math.Abs(Precision.Magnitude(stopCriterium)) + 1;
            if (Precision.IsSmallerWithDecimalPlaces(residualNorm, stopCriterium, decimalMagnitude))
            //if (residualNorm <= stopCriterium)
            {
                if (m_LastIteration <= iterationNumber)
                {
                    m_IterationCount = iterationNumber - m_LastIteration;
                    if (m_IterationCount >= m_MinimumIterationsBelowMaximum)
                    {
                        SetStatusToConverged();
                    }
                    else
                    {
                        SetStatusToRunning();
                    }
                }
            }
            else
            {
                m_IterationCount = 0;
                SetStatusToRunning();
            }

            m_LastIteration = iterationNumber;
        }

        private double ComputeStopCriterium(double solutionNorm)
        {
            // This is criterium 1 from Templates for the solution of linear systems.
            // The problem with this criterium is that it's not limiting enough. For now 
            // we won't use it. Later on we might get back to it.
            //return mMaximumResidual * (System.Math.Abs(mMatrixNorm) * System.Math.Abs(solutionNorm) + System.Math.Abs(mVectorNorm));

            // For now use criterium 2 from Templates for the solution of linear systems. See page 60.
            return m_Maximum * System.Math.Abs(solutionNorm);
        }

        private void SetStatusToDiverged()
        {
            if (!(m_Status is CalculationDiverged))
            {
                m_Status = new CalculationDiverged();
            }
        }

        private void SetStatusToConverged()
        {
            if (!(m_Status is CalculationConverged))
            {
                m_Status = new CalculationConverged();
            }
        }

        private void SetStatusToRunning()
        {
            if (!(m_Status is CalculationRunning))
            {
                m_Status = new CalculationRunning();
            }
        }

        /// <summary>
        /// Returns the current calculation status.
        /// </summary>
        public ICalculationStatus Status
        {
            [DebuggerStepThrough]
            get
            {
                return m_Status;
            }
        }

        /// <summary>
        /// Resets the <c>IIterationStopCriterium</c> to the pre-calculation state.
        /// </summary>
        public void ResetToPrecalculationState()
        {
            m_Status = sm_DefaultStatus;
            m_IterationCount = 0;
            m_LastIteration = sm_DefaultLastIterationNumber;
        }

        /// <summary>
        /// Returns the <c>StopLevel</c> which indicates what sort of stop criterium this
        /// <c>IIterationStopCriterium</c> monitors.
        /// </summary>
        /// <value>Returns <see cref="dnAnalytics.LinearAlgebra.Solvers.StopLevel.Convergence"/>.</value>
        public StopLevel StopLevel
        {
            [DebuggerStepThrough]
            get
            {
                return StopLevel.Convergence;
            }
        }

        /// <summary>
        /// Clones the current <c>ResidualStopCriterium</c> and its settings.
        /// </summary>
        /// <returns>A new instance of the <c>ResidualStopCriterium</c> class.</returns>
        public IIterationStopCriterium Clone()
        {
            return new ResidualStopCriterium(m_Maximum, m_MinimumIterationsBelowMaximum);
        }

        object ICloneable.Clone()
        {
            return Clone();
        }
    }
}
